package com.orange.core.security.entrypoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.core.pojo.R;
import com.orange.core.pojo.enums.EErrorCode;
import com.orange.core.util.Constants;
import com.orange.core.util.TokenUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@AllArgsConstructor
public class AccessForbiddenEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        log.warn("访问被拒绝：{}，{}", request.getRequestURI(), authException.getMessage());
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON_UTF8_VALUE);
        response.setHeader(Constants.TOKEN_KEY, TokenUtil.getToken(request, true));
        PrintWriter writer = response.getWriter();
        writer.write(objectMapper.writeValueAsString(R.fail(EErrorCode.ACCESS_DENIED)));
    }
}
